﻿using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using 微信信息管理系统.Code.Model;

namespace 微信信息管理系统.Code.Service;

[AppAuthorize]
public class UserService : IDynamicApiController
{
    private readonly IFreeSql _fsql;

    public UserService(IFreeSql fsql)
    {
        _fsql = fsql;
    }

    // 获取分页列表
    public async Task<Res<PageResult<User>>> PostPage(PageInput input)
    {
        var query = _fsql.Select<User>();
        if (!string.IsNullOrEmpty(input.Keywords))
        {
            query.Where(x =>
                x.Name.Contains(input.Keywords) ||
                x.Tel.Contains(input.Keywords) ||
                x.CompanyName.Contains(input.Keywords) ||
                x.NickName.Contains(input.Keywords) ||
                x.OpenId.Contains(input.Keywords)
            );
        }

        var result = await query.OrderByDescending(x => x.Id).Count(out long count).Page(input.Page, input.PerPage).ToListAsync();

        return new Res<PageResult<User>>(new PageResult<User>
            {
                count = (int) count,
                rows = result
            }
        );
    }

    public async Task<Res<object>> PostSetState(int id, UserState state)
    {
        var user = await _fsql.Update<User>().Set(it => it.UserState == state).Where(x => x.Id == id).ExecuteAffrowsAsync();
        return new Res<object>();
    }

    public async Task<Res<User>> Get(int id)
    {
        var user = await _fsql.Select<User>().Where(x => x.Id == id).ToOneAsync();
        return new Res<User>(user);
    }
    
    [AllowAnonymous]
    public async Task<Res<User>> Post(User user)
    {
        try
        {
            user.UserState = UserState.待审核;
            var result = await _fsql.Insert<User>(user).ExecuteAffrowsAsync();
            return new Res<User>(user);
        }
        catch (Exception e)
        {
            return new Res<User>("信息已经提交过了！", false);
        }
    }


    public async Task<Res<User>> Delete(int id)
    {
        var result = await _fsql.Delete<User>(id).ExecuteAffrowsAsync();
        return new Res<User>(null);
    }
}